﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Domain.Entities;

namespace wt.wine.Infrastructure.Persistence.Repository
{
    /// <summary>
    /// 角色权限
    /// </summary>
    public class MenuTableRepository : IMenuTableRepository
    {
        private readonly IApplicationDbContext _dbcontext;
        private readonly IMemoryCache _cache;
        public MenuTableRepository(IApplicationDbContext dbcontext, IMemoryCache cache)
        {
            _dbcontext = dbcontext;
            _cache = cache;
        }

        /// <summary>
        /// 通过角色id获取角色权限
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="isRedisKey"></param>
        /// <param name="cancellationtoken"></param>
        /// <returns></returns>
        public async Task<List<menutable>> GetMenuTableList(int roleid, int isRedisKey, CancellationToken cancellationtoken)
        {
            List<menutable> list = new List<menutable>() { };
            string key = "rolePermissionid" + roleid;
            if (isRedisKey == 1)
            {
                //menutable
                list = _cache.Get<List<menutable>>(key);
                if (list != null)
                {
                    return list;
                }
            }
            list = await _dbcontext.menutable.AsNoTracking().Where(p => p.ifshow == 1).ToListAsync(cancellationtoken);
            list = list == null ? new List<menutable>() { } : list;
            list.ForEach(p => { p.ifshow = 0; });
            var list_role = await _dbcontext.rolemenutable.AsNoTracking().Where(p => p.roleid == roleid && p.state >= 0).ToListAsync(cancellationtoken);
            if (list.Any() && list_role != null && list_role.Any())
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    if (list_role.Where(p => p.meunid == list[i].id).Count() > 0)
                    {
                        list[i].ifshow = 1;
                    }
                }
            }



            _cache.Set<List<menutable>>(key, list, TimeSpan.FromDays(2));
            return list;
        }

    }
}
